﻿using System.Linq;

using Whoever.Framework.CustomException;
using Whoever.Framework.Enum;
using Whoever.Framework.Utils;
using Whoever.Patterns.Business;

using EditorialProyectos.Business.Entities;
using EditorialProyectos.DataAccess.Repositories;
using EditorialProyectos.Business.Entities.Enum;

namespace EditorialProyectos.Business
{
    public class ProfileManager : Manager<Profile>
    {
        public ProfileManager()
            : base(RepositoryFactory.ProfileRepository)
        {
        }

        public Profile SignUp(Profile profile)
        {
            if (!ManagerFactory.UserManager.AccountExists(profile.User.Account))
            {
                var originalPass = profile.User.Password;
                profile.User.Password = Cryptography.Encrypt(profile.User.Password);
                profile.User.RoleId = (int)RoleType.User;
                Repository.Insert(profile);
                var newProfile = Repository.GetAllRelated().SingleOrDefault(e => e.User.Account == profile.User.Account);
                newProfile.User.Password = originalPass;
                newProfile.User = ManagerFactory.UserManager.Login(newProfile.User);
                return newProfile;
            }
            else
                throw new BusinessException(Localized.Message("AccountAlreadyExists", MessageType.Error));
        }        
    }
}
